/*
 * @Author: Jason Liu
 * @Date: 2025-06-05 13:19:40
 * @Desc: 
 */

const hdwDataSource = {
  clusterId: undefined,
  dbId: undefined, //数据源ID
  dbSchema: undefined, //SchemaName
  tableCode: undefined, // 数据表code
  columnName: undefined // 列名称
};

const $metaService = require("w-vue-chongqing/src/api/metadata");
const $modelService = require("w-vue-chongqing/src/api/dataModel");

const $userService = require("w-vue-chongqing/src/api/userService");

const indicatorSelection = require("w-vue-chongqing/integratSchedue/indicatorSelection")
  .default;

const {
  oldSourceSelection: sourceSelection,
  tableSelection
} = require("w-vue-middle/dataSourceService");

//基础模型信息
const hdwBasicModel = {
  id: undefined,
  datasourceId: undefined, // 目标数据源id
  schemaName: undefined, // 目标数据源schema
  indicatorCode: undefined, // 指标code
  indicatorName: undefined, // 指标name
  tableId: undefined, // 表id
  tableCode: undefined, // 表code
  tableName: undefined, // 表name
  tableSno: undefined, // 表编码
  sourceDatasourceId: undefined, // 来源数据源id
  sourceSchemaName: undefined, // 来源数据源schema
  sourceTableCode: undefined, // 来源数据源tableCode
  sourceColumnList: [], // 来源表的columns
  isManual: "1",
  columnList: [],
  indicatorList: []
};

export default {
  components: { sourceSelection, tableSelection, indicatorSelection },
  props: {
    value: {
      type: Object,
      default: () => {
        return {
          id: undefined,
          datasourceId: undefined, // 目标数据源id
          schemaName: undefined, // 目标数据源schema
          indicatorCode: undefined, // 指标code
          indicatorName: undefined, // 指标name
          tableId: undefined, // 表id
          tableCode: undefined, // 表code
          tableName: undefined, // 表name
          tableSno: undefined, // 表编码
          sourceDatasourceId: undefined, // 来源数据源id
          sourceSchemaName: undefined, // 来源数据源schema
          sourceTableCode: undefined, // 来源数据源tableCode
          sourceColumnList: [], // 来源表的columns
          isManual: "1",
          columnList: [],
          indicatorList: []
        };
      }
    },
    indicatorInfo: {
      type: Object,
      default: () => {
        return {
          id: undefined,
          code: undefined,
          name: undefined
        };
      }
    },
    sourceHdws: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      loading: false,
      visible: this.show,
      model: {
        ...hdwBasicModel,
        ...this.value
      },
      dataSource: JSON.DeepCopy(hdwDataSource),
      targetDataSource: JSON.DeepCopy(hdwDataSource),
      viewIndicatorSelect: false,
      activeKey: "hwdBasic"
    };
  },
  created() {
    this.init();
  },
  methods: {
    handleMenuClick(e) {
      this.$emit("setMdeol", e);
    },
    /**
     * @Author: Jason Liu
     * @description: 删除关联指标
     */
    deleteIndicator(i) {
      //this.model.indicatorList.splice(i, 1);
    },
    /**
     * @Author: Jason Liu
     * @description: 初始化默认数据
     */
    init() {
      console.log("init>>>>>>>>>")
      if (this.model.id) {
        this.model = this.value;
        const {
          sourceDatasourceId,
          sourceSchemaName,
          sourceTableCode,
          datasourceId,
          schemaName
        } = this.model;
        this.dataSource = {
          dbId: sourceDatasourceId,
          dbSchema: sourceSchemaName,
          tableCode: sourceTableCode
        };
        this.targetDataSource = {
          dbId: datasourceId,
          dbSchema: schemaName
        };
      } else {
        const source = $storage.get("metadata_hdw_default_source").toJson();
        const target = $storage.get("metadata_hdw_default_target").toJson();

        this.dataSource = JSON.DeepCopy({
          ...hdwDataSource,
          ...source
        });

        this.targetDataSource = JSON.DeepCopy({
          ...hdwDataSource,
          ...target
        });

        this.model.sourceDatasourceId = this.dataSource.dbId;
        this.model.sourceSchemaName = this.dataSource.dbSchema;

        const { dbId, dbSchema } = this.targetDataSource;
        this.model.datasourceId = dbId;
        this.model.schemaName = dbSchema;

        this.updateModel();
      }
    },
    /**
     * @Author: Jason Liu
     * @description: 修改目标数据源
     */
    changeTarget() {
      const { dbId, dbSchema, clusterId } = this.targetDataSource;
      this.model.datasourceId = dbId;
      this.model.schemaName = dbSchema;
      this.model.clusterId = clusterId;  //保存时同步字段需要
      this.updateModel();
    },
    // 选择表
    changeTable(val) {
      // 模型编码和表英文默认一致
      if (!this.model.id) {
        this.model.sourceTableCode = this.model.tableSno = this.model.tableName = `${val}`;
        this.model.tableCode = `${val}`.toLocaleLowerCase();
      }

      this.loading = true;
      const { clusterId, dbId, dbSchema, tableCode } = this.dataSource;

      this.model.sourceDatasourceId = dbId;
      this.model.sourceSchemaName = dbSchema;
      this.model.sourceTableCode = tableCode;
      
      // 解决切换表时，model里面目标数据被清掉问题
      this.model.datasourceId = this.targetDataSource.dbId;
      this.model.schemaName = this.targetDataSource.dbSchema;
      this.model.clusterId = this.targetDataSource.clusterId;

      $userService
        .collectionDataInfo({
          clusterId,
          collectType: "column", // 采集类型：schema、table、column
          dsId: dbId,
          schema: dbSchema,
          tableName: tableCode
        })
        .then(({ data }) => {
          let list = data.map(item => {
            return {
              columnCode: item.columnName,
              columnName: item.description,
              columnType: item.columnType,
              columnSize: item.columnSize,
              columnAccuracy: item.columnAccuracy,
              defaultValue: "",
              isNull: item.notNull,
              pk: item.pk,
              tableId: undefined,
              id: undefined
            };
          });
          this.model.sourceColumnList = JSON.DeepCopy(list);
          this.model.columnList = list;
          this.updateModel();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * @Author: Jason Liu
     * @description: 切换模型名
     */
    changeTabldeCode(e) {
      this.model.tableCode = e.target.value.replace(/[\u4e00-\u9fff\u3400-\u4DBf]/g, '').toLocaleLowerCase();
      this.$emit("changeTableCode", { ...this.model });
    },
    /**
     * @Author: Jason Liu
     * @description: 更新模型信息
     */
    updateModel() {
      this.$emit("input", this.model);
      this.$emit("change", {...this.model});
    },
    /**
     * @Author: Jason Liu
     * @description: 添加新的指标
     */
    addNewIndicator({ id, name, code }) {
      let has = this.model.indicatorList.find(item => {
        return item.id == id;
      });
      if (!has) {
        this.model.indicatorList.push({
          //id: id,
          indicatorCode: code,
          indicatorName: name
        });
      }
    }
  },
  watch: {
    value(val) {
      if (this.model.id != val.id) {
        this.init();
      }
      this.model = val;
    },
    model(val) {
      this.$emit("input", val);
    }
  }
};
